<?php

namespace app\store\model\appointment;

use app\common\model\BaseModel;


/**
 * 预约时间模型
 * Class PointsLog
 * @package app\store\model\user
 */
class Time extends BaseModel
{
    protected $name = 'appointment_time';

    /**
     *  预约时间
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getList($param = [])
    {
        // 获取列表数据
        return $this->where('is_delete', 0)
            ->where('status', 1)
            ->where($param)
            ->order('sort asc')
            ->field('time_id,name')->select();
    }

    /**
     * 预约类型
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getListByPage()
    {
        // 获取列表数据
        return $this->where('is_delete', 0)
            ->order('type_id asc,sort asc')->paginate(15, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) {
                $item['type_name'] = Db("appointment_type")
                    ->where('type_id', $item['type_id'])->value('name');
            });
    }

    /**
     * 新增记录
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function add($data)
    {
        if (!$this->validateForm($data)) {
            return false;
        }
        $data['wxapp_id'] = self::$wxapp_id;
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑记录
     * @param $data
     * @return false|int
     */
    public function edit($data)
    {
        if (!$this->validateForm($data, 'edit')) {
            return false;
        }
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 类型详情
     * @param $grade_id
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($type_id, $with = [])
    {
        return static::get($type_id, $with);
    }

    /**
     * 表单验证
     * @param $data
     * @param string $scene
     * @return bool
     */
    private function validateForm($data, $scene = 'add')
    {
        if ($scene === 'add') {
            $exist = Db("appointment_time")
                ->where('name', $data['name'])
                ->where('type_id', $data['type_id'])
                ->where('wxapp_id', self::$wxapp_id)
                ->value('time_id');
            if ($exist) {
                $this->error = '名称已存在';
                return false;
            }
        } elseif ($scene === 'edit') {
            $exist = Db("appointment_time")
                ->where('time_id', 'neq', $this['time_id'])
                ->where('name', $data['name'])
                ->where('type_id', $data['type_id'])
                ->where('wxapp_id', self::$wxapp_id)
                ->value('time_id');
            if ($exist) {
                $this->error = '名称已存在';
                return false;
            }
        }
        return true;
    }


    /*
     * 获取可预约的时间段列表
     */

    public static function useTimeList($type_id,$date){

        $where = [
            'wxapp_id' => self::$wxapp_id,
            'is_delete' => 0,
            'type_id' => $type_id,
        ];

        $count = Db("appointment_type")
            ->where($where)
            ->value('count');
        $list = Self::where($where)
            ->where('status', 1)
            ->field('time_id,name,desc')
            ->order("sort asc")
            ->select()->toArray();

        $cur_date = strtotime(date("Y-m-d", time()));
        $lower_state = $cur_date - $date == 0 ? 1 : 0;
        foreach ($list as $k => $v) {
            $use_count = Db("appointment_order")
                ->where("appointment_date", $date)
                ->where("time_id", $v['time_id'])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->count();

            $state = false;
            $arr = explode('~', $v['desc']);
            if ($lower_state && count($arr) == 2) {
                $m1 = getMinute(date("H:m", time()));
                $m2 = getMinute($arr[1]);
                if ($m1 >= $m2) {
                    $list[$k]['use_count'] = 0;
                    $state = true;
                    unset($list[$k]);
                }
            }

            if (!$state) {
                $config_count = Db("appointment_config")
                    ->where("type_id", $type_id)
                    ->where("date", $date)
                    ->where("time_id", $v['time_id'])
                    ->where($where)->find();
                $all_count = isset($config_count['count']) ? $config_count['count'] : $count;
                if(($all_count - $use_count) == 0){
                    unset($list[$k]);
                }
            }
        }
        $list = array_values($list);
        return $list;
    }

}